package com.zjw.filter;

import com.alibaba.fastjson.JSON;
import com.zjw.constants.SystemConstants;
import com.zjw.annotation.domain.ResponseResult;
import com.zjw.annotation.domain.entity.User;
import com.zjw.enums.AppHttpCodeEnum;
import com.zjw.service.impl.LoginUser;
import com.zjw.utils.JwtUtil;
import com.zjw.utils.RedisCache;
import com.zjw.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {

//        尝试从请求头中获取token
        String token = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(token)) {
//            没有token内容，表示请求不需要token直接放行，如果需要token却没携带会被Security权限系统过滤
//            System.out.println("直接放行");
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
//        解析jwt
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("------------------------------------");
            System.out.println("-------------错误token---------------");
            System.out.println("-------------错误token---------------");
//            1. jwt过期
//            2. jwt非法
//            因为现在在过滤器，还没有到controller层，所不能直接通过new ResponseResult返回, 且这里的异常不会被统一处理捕获
//            所以要通过修改响应体进行返回；使用自定义工具类; 工具类的方法会将Json字符串写入响应中
            WebUtils.renderString(
                    httpServletResponse,
                    JSON.toJSONString(ResponseResult.errorResult(AppHttpCodeEnum.JWT_ERR))
            );
            return;
        }
//        从Redis中获取对应用户对象
//        claims.getSubject()返回的是userId
        User cacheObject = redisCache.getCacheObject(SystemConstants.JWT_KEY_PREFIX + claims.getSubject());

//        如果Redis中查找不到，响应失败信息给前台
        if(cacheObject == null){
            WebUtils.renderString(
                    httpServletResponse,
                    JSON.toJSONString(ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN))
            );
            return;
        }


//        将用户对象存入SecurityContextHolder中
//        存入之前要先封装成AbstractAuthenticationToken的实现类对象
        UsernamePasswordAuthenticationToken curUser = new UsernamePasswordAuthenticationToken(
                new LoginUser(cacheObject, null),
                null,
                null
        );
        SecurityContextHolder.getContext().setAuthentication(curUser);

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
